<?php
/**
 * 固定微信登录逻辑
 * 1.使用phoneCode和loginCode获取到手机号和openid并在表中创建或更新用户
 * 2.处理完用户信息后创建登录凭证token并返回有效时间
 * 3.前端根据token返回用户信息，之后的逻辑前端进行处理
 */
namespace app\api\controller;

use app\api\service\User;
use app\common\controller\ApiController;
use app\common\lib\Show;
use think\facade\Cache;

class WeChat extends ApiController
{

    public function wxLogin(): \think\response\Json
    {
        if(!$this->request->isPost()){
            return Show::error([],'请求方式错误');
        }
        $loginCode=$this->request->post('loginCode');
        $phoneData=$this->request->post('phoneCode');
        if(empty($loginCode)||empty($phoneData)){
            return Show::error([],'参数错误');
        }
        $expire=1296000;
        try {
            $openId=\app\api\service\WeChat::doLogin($loginCode);
            $phone=\app\api\service\WeChat::getPhoneNumberByCode($phoneData);
            $userData=['open_id'=>$openId,'phone'=>$phone];
            $uid=User::saveUser($userData);
            $token=$this->createLoginToken($openId);
            Cache::set($token,['open_id'=>$openId,'uid'=>$uid],$expire);
        }catch (\Exception $e){
            return Show::error([],$e->getMessage());
        }
        return Show::success(['token'=>$token,'expire'=>$expire]);
    }

    private function createLoginToken($string): string
    {
        //生成token
        $str = md5(uniqid(md5(microtime())));//生成一个不会重复的字符串
        return sha1($str . $string);
    }
}